package com.shy.base.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 日期操作工具类
 * 
 * @author H2013788
 */
public class DateUtils {
	
	public static void main(String[] args) {
		System.out.println(setDateMinTime(new Date()));
		System.out.println(setDateMaxTime(new Date()));
	}
	

    /**
     * 设置日期时间為最小时间 00:00:00
     * 
     * @param date 日期
     * @return
     * @author H2013788
     * @date 2017/12/20下午2:59:03
     */
    public static Date setDateMinTime(Date date) {
        if (null != date) {
        	Calendar calendarStart = Calendar.getInstance();
			calendarStart.setTime(date);
			calendarStart.set(calendarStart.get(Calendar.YEAR),
			calendarStart.get(Calendar.MONTH),
			calendarStart.get(Calendar.DATE),0, 0, 0);
			date = calendarStart.getTime();
			return date;
        }
        return null;
    }

    /**
     * 设置日期时间為最大时间 23:59:59
     * 
     * @param date 日期
     * @return
     * @author H2013788
     * @date 2017/12/20下午2:59:21
     */
    public static Date setDateMaxTime(Date date) {
        if (null != date) {
        	Calendar calendarStart = Calendar.getInstance();
			calendarStart.setTime(date);
			calendarStart.set(calendarStart.get(Calendar.YEAR),
			calendarStart.get(Calendar.MONTH),
			calendarStart.get(Calendar.DATE),23, 59, 59);
			date = calendarStart.getTime();
			return date;
        }
        return null;
    }

    /**
     * 格式化日期，如2017-12-20 10:11:20 --> 2017-12-20
     * 
     * @param date
     *            日期
     * @param pattern
     *            格式
     * @return
     * @author H2013788
     * @date 2017/12/20上午11:50:57
     */
    public static Date dateFormat(Date date, String pattern) {
        String dateStr = dateConvert2Str(pattern, date);
        return strConvert2Date(pattern, dateStr);
    }

    /**
     * 转换成指定的日期时间格式
     * 
     * @param pattern
     *            时间格式
     * @param sourceDate
     *            日期
     */
    public static String dateConvert2Str(String pattern, Date sourceDate) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(sourceDate);
    }

    /**
     * 字符串格式转化为Date日期格式
     * 
     * @param pattern
     *            时间格式
     * @param dateStr
     *            日期字符串
     */
    public static Date strConvert2Date(String pattern, String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 转换成指定的日期时间格式（英文版）
     * 
     * @param pattern
     *            日期格式
     * @param sourceDate
     *            日期
     */
    public static String dateConvert2StrEn(String pattern, Date sourceDate) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.ENGLISH);
        return sdf.format(sourceDate);
    }

    /**
     * 字符串格式转化为Date日期格式（英文版）
     * 
     * @param pattern
     *            时间格式
     * @param dateStr
     *            日期字符串
     */
    public static Date strConvert2DateEn(String pattern, String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.ENGLISH);
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 比较日期大小
     * 
     * @param date1
     *            日期1
     * @param date2
     *            日期2
     * @param pattern
     *            格式
     * @return
     */
    public static int compareDate(String date1, String date2, String pattern) {
        DateFormat df = new SimpleDateFormat(pattern);
        try {
            Date dt1 = df.parse(date1);
            Date dt2 = df.parse(date2);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取指定日期位於当前年的第幾周
     * 
     * @param date
     *            日期
     * @return
     * @author H2013788
     * @date 2017/12/7下午7:31:39
     */
    public static int getWeekOfYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.WEEK_OF_YEAR);
    }
    
    /**
     * 日期添加天数
     * @param date
     * @return
     * @author H2013788
     * @date 2019年7月30日
     */
    public static Date addDay(Date date, int days) {
    	Calendar calendar = Calendar.getInstance();
    	calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - days);
        return calendar.getTime();
    }
    
    
    
    private static String formatChange(String format){
		String timeStr=format;
		int len1=timeStr.length();
		int len2=timeStr.replaceAll("'", "").length();
		int count=len1-len2;
		//format串中有''字符串標示符		
		if(count>0){
			//''字符未成對出現，直接返回
			if(count%2!=0){
				return "";
			}
			//對format做大小寫轉換
			String[] ss=timeStr.split("'");
			StringBuffer sb=new StringBuffer();
			int i=1;
			for(String s:ss){
				if(i%2==0){
				  sb.append("'").append(s).append("'");
				}else{
					String tmp=s.replaceAll("Y", "y");
					tmp=tmp.replaceAll("D", "d");
					sb.append(tmp);
				}
				i++;
			}
			format=sb.toString();
		}else{
			String tmp=timeStr.replaceAll("Y", "y");
			tmp=tmp.replaceAll("D", "d");
			format=tmp;
		}
		return format;
	}
    
    
    /**
	 * 按格式，获得当前时间字符串表示
	 * @param format 
	 * 格式：YYYY-MM-DD hh:mm:ss及YYyy-MM-dD hh:mm:ss 
	 * 會統一轉化為SimpleDateFormat要求的標準格式yyyy-MM-dd hh:mm:ss
	 * @return
	 */
	public static String getNowTime(String format){
		Calendar c = Calendar.getInstance();		
        format=formatChange(format);
		return new SimpleDateFormat(format).format(c.getTime());
	}
    
    public static String getMonth(){
		return getNowTime("MM");
	}
    
	public static int getMonthInt(){
		String mm=getNowTime("MM");
		return Integer.parseInt(mm);
	}
	
	public static String getYear(){
		return getNowTime("YYYY");
	}
	
	public static int getYearInt(){
		String mm=getNowTime("YYYY");
		return Integer.parseInt(mm);
	}
	
	public static String getDay(){
       return getNowTime("DD");
    }
	

	/**
	 * 計算兩個时间的时间差
	 * @param sdate
	 * @param bdate
	 * @return
	 * @author H2013788
	 * @date 2019年7月19日
	 */
	public static Map<String, String> timesBetween(Date startDate, Date endDate) {
		long day = 0;
		long hour = 0;
		long min = 0;
		long sec = 0;
		long diff = 0;
		long stime = startDate.getTime();
		long btime = endDate.getTime();
		if (stime > btime) {
			diff = stime - btime;
		} else {
			diff = btime - stime;
		}
		day = diff / (24 * 60 * 60 * 1000);
		hour = diff / (60 * 60 * 1000) - day * 24;
		min = diff / (60 * 1000) - day * 24 * 60 - hour * 60;
		sec = diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60;
		Map<String, String> timeMap = new HashMap<String, String>();
		if(day > 0) {
			timeMap.put("day", String.valueOf(day));
		}
		if(hour > 0) { 
			timeMap.put("hour", String.valueOf(hour));
		}
		if(min > 0) {
			timeMap.put("min", String.valueOf(min));
		}
		if(sec > 0) {
			timeMap.put("sec", String.valueOf(sec));
		}
		return timeMap;
	}

}
